using System;
using System.Collections.Generic;
using System.IO;
using Admin3000.Backend.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace Admin3000.Backend.Api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class FilesController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public FilesController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 文件上传接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, Route("uploadfiles")]
        public string UploadFiles(IFormCollection model)
        {
            // 获得当前应用所在的完整路径（绝对地址）
            var filePath = Directory.GetCurrentDirectory();

            // 通过配置文件获得存放文件的相对路径
            string path = _configuration["UploadFilesPath"];

            // 最终存放文件的完整路径
            var preFullPath = Path.Combine(filePath, path);
            // 如果路径不存在，则创建
            if (!Directory.Exists(preFullPath))
            {
                Directory.CreateDirectory(preFullPath);
            }

            var resultPath = new List<string>();
            foreach (IFormFile file in model.Files)
            {
                if (file.Length > 0)
                {
                    var fileName = file.FileName;
                    var extName = fileName.Substring(fileName.LastIndexOf("."));//extName包含了“.”
                    var tempPath = Path.Combine(path, Guid.NewGuid().ToString("N") + extName);
                    using (var stream = new FileStream(Path.Combine(filePath, tempPath), FileMode.CreateNew))//Path.Combine(_env.WebRootPath, fileName)
                    {
                        file.CopyTo(stream);
                    }

                    // 此处地址可能带有两个反斜杠，虽然也能用，比较奇怪，统一转换成斜杠，这样在任何平台都有一样的表现
                    resultPath.Add(tempPath.Replace("\\", "/"));
                }
            }

            var res = new
            {
                Code = 1000,
                Data = resultPath,
                Msg = "上传成功"
            };

            return JsonHelper.Serialize(res);
        }

        [AllowAnonymous]
        [Route("{prePath}")]
        [HttpGet]
        public FileContentResult Get(string prePath)
        {
           prePath =prePath;
           
            var currentPath = Directory.GetCurrentDirectory();
            var fullPath = Path.Combine(currentPath, prePath);
            using (var sw = new FileStream(fullPath, FileMode.Open))
            {
                var fileType = GetFileTypeWithFileName(fullPath);
                var bytes = new byte[sw.Length];
                sw.Read(bytes, 0, bytes.Length);
                sw.Close();
                return new FileContentResult(bytes, fileType);
            };
            
        }

        /// <summary>
        /// 注册表获取文件类型
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string GetFileTypeWithFileName(string fileName)
        {
            //获取文件后缀
            string ext = Path.GetExtension(fileName);
            using (Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext))
            {
                if (registryKey == null)
                    return null;
                var value = registryKey.GetValue("Content Type");
                return value?.ToString();
            }
        }
    }
}